package com.xayy.scheduled;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class CronTaskRegistrar implements DisposableBean {

    private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);

    @Autowired
    private TaskScheduler taskScheduler;

    public TaskScheduler getScheduler() {
        return this.taskScheduler;
    }

    public void addCronTask(Runnable task, String cronExpression) {
        //如果cron表达式>6说明包含年份，直接转成日期执行
        String[] cronStr=cronExpression.split(" ");
        if(cronStr.length>6){
            String dateStr=cronStr[6]+"-"+cronStr[4]+"-"+cronStr[3]+" "+cronStr[2]+":"+cronStr[1]+":"+cronStr[0];
            Date cronDate= DateUtil.parse(dateStr, DatePattern.NORM_DATETIME_FORMAT);
            addDateTask(new DateTask(task, cronDate));
        }else{
            addCronTask(new CronTask(task, cronExpression));
        }
    }

    public void addCronTask(CronTask cronTask) {
        if (cronTask != null) {
            Runnable task = cronTask.getRunnable();
            if (this.scheduledTasks.containsKey(task)) {
                removeCronTask(task);
            }
            this.scheduledTasks.put(task, scheduleCronTask(cronTask));
        }
    }
    public void addDateTask(DateTask dateTask) {
        if (dateTask != null) {
            Runnable task = dateTask.getRunnable();
            if (this.scheduledTasks.containsKey(task)) {
                removeCronTask(task);
            }
            this.scheduledTasks.put(task, scheduleDateTask(dateTask));
        }
    }
    public void removeCronTask(Runnable task) {
        ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
        if (scheduledTask != null)
            scheduledTask.cancel();
    }

    public ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future =null;
        scheduledTask.future= this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());

        return scheduledTask;
    }
    public ScheduledTask scheduleDateTask(DateTask dateTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future =null;
        scheduledTask.future=this.taskScheduler.schedule(dateTask.getRunnable(),dateTask.runDate);
        return scheduledTask;
    }

    @Override
    public void destroy() {
        for (ScheduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }

        this.scheduledTasks.clear();
    }
}
